#!/usr/bin/env python
# -*- coding:utf-8 -*-

import json

from io import BytesIO
from django.shortcuts import HttpResponse, render, redirect
from django.views import View
from django.conf import settings
from django.utils.module_loading import import_string

from rbac.utils.encrypt import md5
from rbac.utils.check_code import create_validate_code

from rbac.forms.account import LoginForm, ChangePasswordForm
from rbac.service.init_permission import init_permission


def check_code(request):
    """
    验证码
    :param request:
    :return:
    """
    stream = BytesIO()
    img, code = create_validate_code()
    img.save(stream, 'PNG')
    request.session['CheckCode'] = code
    return HttpResponse(stream.getvalue())


def login(request):
    """
    用户登录
    :param request:
    :return:
    """
    if request.method == 'GET':
        return render(request, 'rbac/login.html')
    elif request.method == 'POST':
        result = {'status': False, 'message': None, 'data': None}
        form = LoginForm(request=request, data=request.POST)
        if form.is_valid():
            username = form.cleaned_data.get('username')
            password = form.cleaned_data.get('password')
            password = md5(password)
            user_class = import_string(settings.RBAC_USER_MODEL_CLASS)
            user = user_class.objects.filter(username=username, password=password).first()
            if not user:
                result['message'] = '用户名或密码错误'
            else:
                result['status'] = True
                result['data'] = settings.RBAC_INDEX_URL
                # 权限初始化
                init_permission(user, request)
                if form.cleaned_data.get('rmb'):
                    request.session.set_expiry(60 * 60 * 24 * 7)
        else:
            if 'check_code' in form.errors:
                result['message'] = '验证码错误或者过期'
            else:
                result['message'] = '用户名或密码错误'
        return HttpResponse(json.dumps(result))


def logout(request):
    """
    用户注销
    :param request:
    :return:
    """
    request.session.delete()
    return redirect(settings.RBAC_LOGIN_URL)


def change_password(request):
    """
    修改密码
    :param request:
    :return:
    """
    if request.method == 'GET':
        form = ChangePasswordForm()
        return render(request, 'rbac/change_password.html', {'form': form})

    form = ChangePasswordForm(request.POST)
    if form.is_valid():
        password = form.cleaned_data['password']
        password = md5(password)
        pk = request.session[settings.RBAC_AUTH_SESSION_KEY]['pk']
        user_class = import_string(settings.RBAC_USER_MODEL_CLASS)
        user_class.objects.filter(pk=pk).update(password=password)

        form = ChangePasswordForm()
        return render(request, 'rbac/change_password.html', {'form': form, 'success': '修改成功'})

    return render(request, 'rbac/change_password.html', {'form': form})
